var restify = require('restify');
var mongomq = require('mongomq');

var constants = require('./constants.js');

/*
 * Mongo MQ Configuration
 */
console.log('creating mongo mq...');
var queue = new mongomq.MongoMQ({
	server: constants.queue.SERVER,
	autoStart: false
});

// set server forcely
queue.mongoConnection.server.host = constants.queue.SERVER;
console.log('mongoConnection: ' + JSON.stringify(queue.mongoConnection));

queue.start(function() {
	console.log('Queue listening started.');
	console.log('active: ' + queue.mongoConnection.active);
});

var respond = function (request, response, next) {
	var result = {message: 'Hello ' + request.params.name};
	response.send(result);
};

/*
 * REST WEB Server Configuration
 */
var server = restify.createServer();
server.use(restify.bodyParser());

server.get('/hello/:name', respond);
server.head('/hello/:name', respond);

server.post('/notification', function(request, response, next) {
	var notification = JSON.parse(request.body);
	console.log("notification: " + JSON.stringify(notification));
	console.log("message: " + notification.message);
	
	if (notification.type == 'mail' || notification.type == 'mobile') {
		queue.emit(notification.type, notification);
		console.log("put message into the queue.");
	}
	
	respond(request, response, next);
});

server.listen(8080, function() {
	console.log('%s listening at %s', server.name, server.url);
});